import React, {Component} from 'react'
import {Button, message, Spin, Table} from "antd"
import moment from 'moment';
import {getRes} from "../../configFile";
import Device from '../../types/Device';
import {connect, ConnectedProps} from 'react-redux'
import {RootState} from '../../reducers';
import {listDevice, listDeviceOnID, queryDeviceAmount, queryDeviceAmountOnID} from '../../requests/Device';
import ButtonGroup from 'antd/lib/button/button-group';
import {RouteComponentProps, withRouter} from 'react-router-dom';
import UserType from '../../types/UserType';
import DeleteDeviceModal from './DeleteDeviceModal'

interface IProps extends RouteComponentProps, ConnectedProps<typeof connector> { }
interface IState {
    deviceSource: Array<Device & { key: number }>
    amount: number
    offset: number
    limit: number
    isLoading: boolean
}

export class ModifyDevice extends Component<IProps, IState> {
    constructor(props: IProps) {
        super(props)
        this.state = {
            isLoading: true,
            deviceSource: [],
            amount: 0,
            offset: 0,
            limit: 10
        }
    }

    //获取设备数据
    getDevice = async () => {
        try {
            this.setState({ isLoading: true });
            //超管用list,设备管理员用onID
            const amountRes = this.props.userType === UserType.SUPERVISOR ?
                getRes(await queryDeviceAmount())
                :
                getRes(await queryDeviceAmountOnID())

            const res = this.props.userType === UserType.SUPERVISOR ?
                getRes(await listDevice(this.state.offset, this.state.limit))
                :
                getRes(await listDeviceOnID(this.state.offset, this.state.limit, this.props.userID))
            if (amountRes.isSuccessful === false) {
                message.error(amountRes.message)
                return;
            }
            if (res.isSuccessful === false) {
                message.error(res.message)
                return;
            }
            this.setState({
                deviceSource: res.data.map((item: Device) => Object.assign({}, item, { key: item.deviceID })),
                amount: amountRes.data
            })
        }
        catch (error) {
            message.error(error.toString())
        } finally {
            this.setState({ isLoading: false })
        }
    }

    componentDidMount() {
        this.getDevice()
    }

    columns = [{
        title: '设备ID',
        dataIndex: 'deviceID',
        key: 'deviceID',
    },
    {
        title: '设备名称',
        dataIndex: 'deviceName',
        key: 'deviceName',
    },
    {
        title: '上次修改时间',
        dataIndex: 'lastModifiedTime',
        key: 'lastModifiedTime',
        render: (record: number) => {
            return moment(record).format('YYYY-MM-DD')
        }
    },
    {
        title: '操作',
        key: 'action',
        render: (record: Device) => (
            <ButtonGroup>
                <Button size='middle' type='primary' onClick={() => {
                    console.log(record);
                    this.props.history.push(`modifyDevice/${record.deviceID}`)
                }}>编辑</Button>
                <Button size='middle' danger onClick={() => {
                    DeleteDeviceModal(record.deviceID, record.deviceName, this.getDevice)
                }}>删除</Button>
            </ButtonGroup>
        )
    }]
    render() {
        return (
            <div>
                <Spin spinning={this.state.isLoading}>
                    <Table columns={this.columns}
                        dataSource={this.state.deviceSource}
                        pagination={{
                            onChange: (page, pageSize) => {
                                console.log(page, pageSize);
                                if (!!pageSize) {
                                    this.setState({
                                        offset: (page - 1) * (pageSize),
                                        limit: (pageSize)
                                    },()=>{
                                        this.getDevice()
                                    })
                                } else {
                                    console.error('pageSize === undefinde')
                                }
                            },
                            defaultPageSize: this.state.limit,
                            total: this.state.amount,
                            showSizeChanger: false
                        }}
                    />
                </Spin>
            </div>
        )
    }
}

//connect加入props
const mapStateToProps = (state: RootState) => {
    return {
        userID: state.loginReducers.userID,
        userType: state.loginReducers.userType
    }
}

const connector = connect(mapStateToProps);
export default withRouter(connector(ModifyDevice));